<!-- eslint-disable no-unused-expressions -->
<template>
  <div class="users-base-wrapper">
    <div class="module-name">
      <div>内嵌设计({{ queryParams.name }})</div>
      <el-button size="mini" type="default" icon="el-icon-arrow-left" @click="handleGoBack">返回上一级</el-button>
    </div>
    <div class="function-details-layout">
      <!-- 按钮区域 -->
      <el-row style="text-align: left; margin-bottom: 16px">
        <el-button type="primary" size="mini" @click="handleRefresh">刷新</el-button>
        <el-button type="primary" size="mini" @click="handleSave" v-if="isOperate">保存</el-button>
      </el-row>
      <!-- 表单区域 -->
      <el-form :rules="rules" ref="formRef" size="mini" :model="formData" label-width="320px">
        <el-form-item label="内嵌表：">
          <el-input style="width: 70%" disabled placeholder="请输入" v-model="formData.surfaceName"></el-input>
        </el-form-item>
        <!-- 表单的表格 -->
        <el-form-item label="显示变量名：">
          <el-table
            v-model="selectedRows"
            :data="inlineBoundaries"
            ref="multipleTable"
            stripe
            style="width: 70%"
            size="mini"
            row-key="id"
            :header-cell-style="{ background: 'rgba(117, 60, 202, 0.04)' }"
            :tree-props="{ children: 'children' }"
          >
            <el-table-column type="index" label="序号" width="50" align="center"></el-table-column>
            <el-table-column prop="variableName" label="变量名" width="300" align="center"></el-table-column>
            <el-table-column prop="display" align="center" label="显示" width="50">
              <!-- 自定义表头 -->
              <template slot="header">
                <el-checkbox v-model="tableHeaderSelectAllVal" @change="handleAllChange"></el-checkbox>
              </template>
              <template slot-scope="scope">
                <el-checkbox v-model="scope.row.display" @change="handleCellChange"></el-checkbox>
              </template>
            </el-table-column>
            <el-table-column prop="only" align="center" label="唯一" width="50">
              <template slot-scope="scope">
                <el-checkbox v-model="scope.row.only"></el-checkbox>
              </template>
            </el-table-column>
            <el-table-column prop="rowInlineControl" align="center" label="行控制" width="120">
              <template slot-scope="scope">
                <el-button
                  type="text"
                  v-if="
                    (scope.row.variableType === '10' || scope.row.variableType === '20') && finallyId !== scope.row.id
                  "
                  @click="handleOpenRowControl(scope.row)"
                >
                  {{ scope.row.rowInlineControl && scope.row.rowInlineControl.length > 0 ? '已设置' : '未设置' }}
                </el-button>
                <span v-else>/</span>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item label="内嵌表模板筛选方式：">
          <el-select v-model="formData.type" placeholder="请选择" style="width: 50%" @change="handleFiltersTypeChange">
            <el-option v-for="item in sectionList" :key="item.value" :label="item.text" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="分页：" v-if="formData.type === '0'">
          <el-radio-group v-model="formData.paging">
            <el-radio label="1">是</el-radio>
            <el-radio label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="表默认值变量：" v-if="formData.type === '2'">
          <el-select v-model="formData.moduleName" placeholder="请选择" style="width: 50%">
            <el-option
              v-for="item in quoteSurfaceVariables"
              :key="item.variable"
              :label="item.variableName"
              :value="item.variable"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="模块名称：" v-if="formData.type === '1'">
          <el-cascader
            :options="embeddedTableCodeGroupList"
            filterable
            :show-all-levels="false"
            v-model="formData.moduleName"
            :props="{
              multiple: false,
              checkStrictly: false,
              value: 'value',
              label: 'label',
              leaf: 'codeName',
              children: 'children',
              emitPath: false,
            }"
            clearable
            style="width: 50%"
          >
          </el-cascader>
        </el-form-item>

        <el-form-item label="变量映射：" v-if="formData.type === '1' || formData.type === '2'">
          <el-input
            style="width: 48%"
            placeholder="请输入"
            type="textarea"
            :rows="3"
            v-model="formData.variableMapping"
            :disabled="true"
            maxlength="200"
            show-word-limit
          ></el-input>
          <el-button type="default" icon="el-icon-more" style="margin-left: 8px" @click="handleOpen"></el-button>
        </el-form-item>
      </el-form>
    </div>
    <add-record
      :searchParams="searchParams"
      :dialogVisible="dialogVisible"
      :editData="editData"
      @handleCancel="handleCancel"
      @handleSubmitValue="handleSubmitValue"
    ></add-record>
    <rowControl
      :rowVisible="rowVisible"
      @handleCancel="handleRowControlCancel"
      :tableColumns="columnData"
      :baseParams="baseParams"
      :controlList="controlList"
      :searchParams="searchParams"
      :rowData="rowData"
      :settingDiaSelectColumn="settingDiaSelectColumn"
    ></rowControl>
  </div>
</template>
<script>
import { mapActions } from 'vuex'
import addRecord from './component/add-record'
import rowControl from './component/row-control.vue'

export default {
  name: 'subject-params',
  components: {
    addRecord,
    rowControl,
  },

  data() {
    return {
      functionParamsData: [],
      formData: {
        surfaceName: '',
        surface: '',
      },
      rules: {
        subjectNumWay: [{ required: true, message: '请选择', trigger: 'blur' }],
        visitFunctionOpen: [{ required: true, message: '请选择', trigger: 'blur' }],
        remindWay: [{ required: true, message: '请选择', trigger: 'blur' }],
        remindScope: [{ required: true, message: '请选择', trigger: 'blur' }],
        dateWay: [{ required: true, message: '请选择', trigger: 'blur' }],
        charDate: [{ required: true, message: '请选择', trigger: 'blur' }],
      },
      sectionList: [
        {
          text: '无',
          value: '0',
        },
        {
          text: '指定',
          value: '1',
        },
        {
          text: '动态获取',
          value: '2',
        },
      ],
      loading: false,
      queryParams: {},
      searchParams: {},
      embeddedTableCodeGroupList: [],
      inlineBoundaries: [],
      dialogVisible: false,
      editData: {},
      quoteSurfaceVariables: [],
      rowVisible: false,
      columnData: [],
      baseParams: '',
      controlList: [],
      finallyId: '',
      rowData: {},
      selectedRows: ['66038e79e4b0f31f366a9db2'],
      tableHeaderSelectAllVal: false,
      // 弹框选择的列数组
      settingDiaSelectColumn: [],
      isOperate: false,
    }
  },

  mounted() {
    this.queryParams = this.$route.query
    const databaseInfo = JSON.parse(localStorage.getItem('sys-database-info')) || {}
    console.log(databaseInfo, 'databaseInfo')
    this.searchParams = {
      projectId: localStorage.getItem('sys-project-id') || '',
      ...databaseInfo,
      surface: this.queryParams.surface,
    }

    if (databaseInfo.isLock === '1') {
      this.isOperate = false
    } else {
      this.isOperate = true
    }

    this.getEmbeddedTableData()
    this.getEmbeddedTableCodeGroupList()
    this.getQuoteSurfaceVariables()
  },

  methods: {
    ...mapActions('eCRFDesign', [
      'qryEmbeddedTableData',
      'qryEmbeddedTableCodeGroupList',
      'qryVariableConfigListNoLoading',
      'qryCodeValueByCodeName',
      'editEmbeddedTableCodeGroupList',
    ]),

    // 所有单元格变化
    handleAllChange(val) {
      this.inlineBoundaries.forEach(item => {
        item.display = val
      })
    },
    // 单个单元格变化
    handleCellChange(val) {
      console.log(this.inlineBoundaries, 'inlineBoundaries')
      const flag = this.inlineBoundaries.every(item => {
        item.display
      })
      this.tableHeaderSelectAllVal = flag
    },

    // 查询内嵌设计详情
    getEmbeddedTableData() {
      const params = {
        ...this.searchParams,
      }
      this.qryEmbeddedTableData({ params }).then(res => {
        const { data, code, message } = res
        if (code === 200) {
          this.functionParamsData = data
          // 获取表格数据
          this.inlineBoundaries = this.formateDataInlineBoundaries(data.inlineBoundaries || [])
          // 判断是否全部被选
          this.tableHeaderSelectAllVal = this.inlineBoundaries.every(item => item.display)
          this.$refs.multipleTable.toggleRowSelection([data.inlineBoundaries[0]], true)
          if (data.inlineBoundaries && data.inlineBoundaries.length > 0) {
            this.finallyId = data.inlineBoundaries[data.inlineBoundaries.length - 1].id
          }
          this.formData = data.boundaryExtend ? { ...data.boundaryExtend } : {}
          this.formData.surfaceName = this.queryParams.surfaceName
        } else {
          this.$message.error(message || '服务异常，请稍后重试!')
        }
      })
    },

    // 返回上一级目录
    handleGoBack() {
      this.$router.go(-1)
    },

    // formate内嵌设计
    formateDataInlineBoundaries(data) {
      data.map(dItem => {
        if (dItem.only === '1') {
          dItem.only = true
        } else {
          dItem.only = false
        }
        if (dItem.display === '1') {
          dItem.display = true
        } else {
          dItem.display = false
        }
      })
      return data
    },

    // 查询引用表的变量
    handleFiltersTypeChange(value) {
      // this.formData.moduleName = ''
      if (value === '2') {
        this.getQuoteSurfaceVariables()
      }
    },

    getQuoteSurfaceVariables() {
      const params = {
        ...this.searchParams,
        surface: this.queryParams.quoteCrf,
      }
      this.qryVariableConfigListNoLoading({ params }).then(res => {
        const { data, code } = res
        if (code === 200) {
          this.quoteSurfaceVariables = data
        }
      })
    },

    // 打开变量映射弹框
    handleOpen() {
      this.editData.variableMapping = this.formData.variableMapping
      this.dialogVisible = true
    },

    handleSubmitValue(value) {
      this.formData.variableMapping = value
      this.dialogVisible = false
    },

    // 取消
    handleRowControlCancel(flag, rowControlJson, rowInlineControl) {
      console.log('flag, rowControlJson, rowInlineControl', flag, rowControlJson, rowInlineControl)
      this.rowVisible = false
      if (flag === 'confirm') {
        this.inlineBoundaries.map((iItem, iIndex) => {
          if (iItem.variable === this.baseParams) {
            iItem.rowInlineControl = rowInlineControl
            iItem.rowControlJson = rowControlJson
          }
        })
        console.log('this.inlineBoundaries', this.inlineBoundaries)
      }
    },

    // 打开行控制弹框
    handleOpenRowControl(row) {
      this.baseParams = row.variable
      this.rowData = row
      const list = []
      let flag = false
      this.inlineBoundaries.map((iItem, iIndex) => {
        if (row.id === iItem.id) {
          flag = true
        }
        if (flag) {
          list.push(iItem)
        }
      })

      const column = []
      list.map((lItem, lIndex) => {
        const obj = {
          key: lItem.variable,
          name: lItem.variableName,
          visible: true,
        }
        column.push(obj)
      })
      // 设置弹窗表格规则
      this.columnData = column
      // 设置弹窗有选择的列
      this.columnData.forEach(item => {
        if (item.key !== 'LBCLSIG' && item.visible) {
          this.settingDiaSelectColumn.push(item.key)
        }
      })
      const codeName =
        row.variableTypeValue && row.variableTypeValue.codeName ? row.variableTypeValue.codeName.split('|')[0] : ''
      this.getCodeValueByCodeName(codeName, row)
    },

    // 根据编码名称获取编码值
    getCodeValueByCodeName(codeName, row) {
      const params = {
        ...this.searchParams,
        code_name: codeName,
      }
      this.qryCodeValueByCodeName({ params }).then(res => {
        const { data, code } = res
        if (code === 200) {
          data.map((dItem, dIndex) => {
            this.columnData.map((cItem, cIndex) => {
              dItem[cItem.key] = false
              dItem.variable = cItem.key
              dItem.variableName = cItem.name
              dItem.crfName = row.surface
              dItem.databaseId = params.databaseId
              dItem.databaseVersion = params.databaseVersion
              dItem.projectId = params.projectId
            })
          })
          this.controlList = data
          this.rowVisible = true
        }
      })
    },

    // 关闭弹框
    handleCancel() {
      this.dialogVisible = false
    },

    // 刷新
    handleRefresh() {
      this.getEmbeddedTableData()
    },

    // 查询内嵌表编码列表
    getEmbeddedTableCodeGroupList() {
      const params = {
        ...this.searchParams,
        environment: '0',
      }
      this.qryEmbeddedTableCodeGroupList({ params }).then(res => {
        const { code, data } = res
        if (code === 200) {
          this.embeddedTableCodeGroupList = this.formateData(data)
        }
      })
    },

    formateData(data) {
      data.map((dItem, dIndex) => {
        dItem.children = []
        if (dItem.codeGroupCn) {
          dItem.label = dItem.codeGroupCn
          dItem.value = dItem.codeGroupCn
        }
        if (dItem.codeNameCn) {
          dItem.label = dItem.codeName + '|' + dItem.codeNameCn
          dItem.value = dItem.codeName + '|' + dItem.codeNameCn
          delete dItem.codeValueVOS
          delete dItem.children
        }
        if (dItem.groupVOS && dItem.groupVOS.length > 0) {
          dItem.children.unshift(...dItem.groupVOS)
          this.formateData(dItem.groupVOS)
        }
      })
      return data
    },

    // 保存
    handleSave() {
      if (!this.formData.type) {
        this.$message.error('请选择内嵌表模版筛选方式')
        return false
      }
      const data = {
        inlineBoundaries: this.formateInlineBoundariesTable(),
        boundaryExtend: {
          ...this.searchParams,
          id:
            this.functionParamsData.boundaryExtend && this.functionParamsData.boundaryExtend.id
              ? this.functionParamsData.boundaryExtend.id
              : '',
          type: this.formData.type,
          paging: this.formData.paging,
          moduleName: this.formData.type !== '0' ? this.formData.moduleName : '',
          variableMapping: this.formData.variableMapping,
          environment: 0,
        },
      }
      console.log(data, 'data')
      this.editEmbeddedTableCodeGroupList({ data }).then(res => {
        const { code } = res
        if (code === 200) {
          this.$message.success('保存成功!')
          this.getEmbeddedTableData()
        }
      })
    },

    // 修改数据
    formateInlineBoundariesTable() {
      const list = []
      this.inlineBoundaries.map(iItem => {
        if (iItem.only) {
          iItem.only = '1'
        } else {
          iItem.only = '0'
        }
        if (iItem.display) {
          iItem.display = '1'
        } else {
          iItem.display = '0'
        }
        list.push(iItem)
      })
      return list
    },
  },
}
</script>
<style lang="scss" scoped>
@import './index.scss';
</style>
